package com.ittao.taoaicodeapp.controller;

import com.ittao.taoaicodeapp.service.ChatHistoryService;
import com.ittao.taoaicodeapp.service.VipLimitService;
import com.ittao.taoaicodeclient.innerservice.InnerUserService;
import com.ittao.taoaicodecommon.annotation.AuthCheck;
import com.ittao.taoaicodecommon.common.BaseResponse;
import com.ittao.taoaicodecommon.common.ResultUtils;
import com.ittao.taoaicodecommon.constant.UserConstant;
import com.ittao.taoaicodecommon.exception.ErrorCode;
import com.ittao.taoaicodecommon.exception.ThrowUtils;
import com.ittao.taoaicodemodel.model.dto.chathistory.ChatHistoryQueryRequest;
import com.ittao.taoaicodemodel.model.entity.ChatHistory;
import com.ittao.taoaicodemodel.model.entity.User;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 对话历史 控制层。
 *
 * @author <a href="https://gitee.com/it-heima-ht">程序员 Tao</a>
 */
@RestController
@RequestMapping("/chatHistory")
public class ChatHistoryController {

    @Resource
    private ChatHistoryService chatHistoryService;

    @Resource
    private VipLimitService vipLimitService;

    /**
     * 分页查询某个应用的对话历史（游标查询）
     *
     * @param appId          应用ID
     * @param pageSize       页面大小
     * @param lastCreateTime 最后一条记录的创建时间
     * @param request        请求
     * @return 对话历史分页
     */
    @GetMapping("/app/{appId}")
    public BaseResponse<Page<ChatHistory>> listAppChatHistory(@PathVariable Long appId,
                                                              @RequestParam(defaultValue = "10") int pageSize,
                                                              @RequestParam(required = false) LocalDateTime lastCreateTime,
                                                              HttpServletRequest request) {
        ThrowUtils.throwIf(appId == null || appId <= 0, ErrorCode.PARAMS_ERROR, "应用ID不能为空");
        ThrowUtils.throwIf(pageSize <= 0 || pageSize > 50, ErrorCode.PARAMS_ERROR, "页面大小必须在1-50之间");

        // 尝试获取登录用户，如果未登录则返回null，使得主页可以观看对应的应用详情
        User loginUser;
        try {
            loginUser = InnerUserService.getLoginUser(request);
        } catch (Exception e) {
            // 用户未登录或登录状态异常，返回null数据
            return ResultUtils.success(null);
        }

        Page<ChatHistory> result = chatHistoryService.listAppChatHistoryByPage(appId, pageSize, lastCreateTime, loginUser);
        return ResultUtils.success(result);
    }

    /**
     * 管理员分页查询所有对话历史
     *
     * @param chatHistoryQueryRequest 查询请求
     * @return 对话历史分页
     */
    @PostMapping("/admin/list/page/vo")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ChatHistory>> listAllChatHistoryByPageForAdmin(@RequestBody ChatHistoryQueryRequest chatHistoryQueryRequest) {
        ThrowUtils.throwIf(chatHistoryQueryRequest == null, ErrorCode.PARAMS_ERROR);
        long pageNum = chatHistoryQueryRequest.getCurrent();
        long pageSize = chatHistoryQueryRequest.getPageSize();
        // 查询数据
        QueryWrapper queryWrapper = chatHistoryService.getQueryWrapper(chatHistoryQueryRequest);
        Page<ChatHistory> result = chatHistoryService.page(Page.of(pageNum, pageSize), queryWrapper);
        return ResultUtils.success(result);
    }

    /**
     * 导出应用的对话历史为Markdown文件
     *
     * @param appId   应用ID
     * @param request 请求
     * @return Markdown文件下载响应
     */
    @GetMapping("/export/{appId}")
    public ResponseEntity<org.springframework.core.io.Resource> exportChatHistory(@PathVariable Long appId,
                                                                                  HttpServletRequest request) {
        User loginUser = InnerUserService.getLoginUser(request);

        // VIP 限制检查：每日导出次数
        vipLimitService.checkAndIncrementDailyExport(loginUser);

        // 调用服务层方法获取Markdown内容
        String markdownContent = chatHistoryService.exportChatHistoryToMarkdown(appId, loginUser);

        // 生成文件名
        String fileName = "chat_history_" + appId + "_"
                + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")) + ".md";

        // 创建字节数组资源
        ByteArrayResource resource = new ByteArrayResource(markdownContent.getBytes(StandardCharsets.UTF_8));

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
        headers.add(HttpHeaders.CONTENT_TYPE, "text/markdown; charset=utf-8");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(resource.contentLength())
                .body(resource);
    }

}
